package com.yjj.demo.common.service;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 *
 *
 * @author yangjiajia
 * @createdAt 2023/1/9 19:40
 */
@Service
public class DingTalkMessageService {

    private Logger logger = LoggerFactory.getLogger(DingTalkMessageService.class);

    private final String defaultRobotUrl = "https://oapi.dingtalk.com/robot/send?access_token=0bb5039adcb0e8644d0099c98c37f1eed17c27b348ee60f8eb66120006e3254b";

    public void sendMsg(String msg) {
        //sendMsg(msg, defaultRobotUrl);
        sendMsg("测试异常提醒", msg, defaultRobotUrl);
    }

    public void sendMsg(String msg, String robotUrl) {
        try {
            DingTalkClient client = new DefaultDingTalkClient(robotUrl);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("text");
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent("**测试:**" + msg + "\n<b>userId:</b>" + UUID.randomUUID());
            request.setText(text);
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            request.setAt(at);
            OapiRobotSendResponse response = client.execute(request);
            logger.info("dingTalk send result:{}", response.getMessage());
        } catch (ApiException e) {
            logger.error("消息发送失败,msg:{}", e.getMessage());
        }
    }

    public void sendMsg(String title, String msg, String robotUrl) {
        try {
            DingTalkClient client = new DefaultDingTalkClient(robotUrl);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("markdown");
            OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
            markdown.setTitle(title);
            String userId = "63329d8cc9e77c00071eaf18";
            //userId = UUID.randomUUID().toString();
            String uri = "/weatapi/redPacket/info";
            String content = String.format("#### **%s**\n\n **用户ID:** %s\n\n **请求路径:** %s\n\n", title, userId, uri);
            //String content = String.format("#### **%s** \n **用户ID:** %s \n **请求路径:** %s\n", title, UUID.randomUUID(), "/api/test/get");
            markdown.setText(content);
            request.setMarkdown(markdown);
//            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
//            request.setAt(at);
            OapiRobotSendResponse response = client.execute(request);
            logger.info("dingTalk send result:{}", response.getMsg());
        } catch (ApiException e) {
            logger.error("消息发送失败,msg:{}", e.getMessage());
        }
    }
}
